<template>
	<div class="page-wrap">
		<div class="page-content">
			<div class="home-middle">
                <Row>
                    <Col span="24">
                        <div class="middle-left" id="homer_Middle">
                            <div class="my-flex">
                                <div class="my-col col-1">
                                    <span class="title">岗位角色学习占比</span>
                                    <div  id="rolePercentage"></div>
                                </div>
                                <!-- <div class="my-col col-2">
                                    <span class="title">课程课件收藏统计</span>
                                    <div  id="rolePercentage"></div>
                                </div> -->
                            </div>
                            <div class="my-flex">
                                <div class="my-col col-2">
                                    <span class="title">视频点赞前十</span>
                                    <div  id="videoLike"></div>
                                </div>
                                <div class="my-col col-2">
                                    <span class="title">视频播放前十</span>
                                    <div  id="videoPlay"></div>
                                </div>
                            </div>
                             <div class="my-flex">
                                <div class="my-col col-2">
                                    <span class="title">试卷使用前十（考试）</span>
                                    <Table :columns="examColumns" :data="examList"></Table>
                                </div>
                                <div class="my-col col-2">
                                    <span class="title">试卷使用前十（自测）</span>
                                    <Table :columns="examColumns" :data="selfTestList"></Table>
                                </div>
                            </div>
                             <div class="my-flex">
                                <div class="my-col col-1">
                                    <span class="title">教学班年度排课前五</span>
                                    <div  id="scoreAnalysis"></div>
                                </div>
                            </div>
                            <div class="my-flex">
                                <div class="my-col col-2">
                                    <span class="title">课程收藏统计</span>
                                    <div  id="Course"></div>
                                </div>
                                <div class="my-col col-2">
                                    <span class="title">课件收藏统计</span>
                                    <div  id="Exp"></div>
                                </div>
                            </div>
                        </div>
                    </Col>
                </Row>
            </div>
		</div>
	</div>
</template>
<script>
import HighCharts from 'highcharts'
import highchartsMore from 'highcharts/highcharts-more';
import * as SeriesLabel from 'highcharts/modules/series-label';
import G2 from '@antv/g2'
import DataSet from '@antv/data-set';
import {getStatisticRoles} from '@/api/role.js'
import {getCountHotCourseAndExp} from '@/api/homer.js'
import {getStatisticsExamPaper} from '@/api/exam.js'
import {queryStudyVideo} from '@/api/videoSelfStudy.js'
import {getStatisticCourseYear} from '@/api/selfStudy/class.js'
	export default {
		components: {
		},
		data() {
			return {
                roleCountList:[],
                roleCountSum:0,
                hotCourseList:[],
                hotExpList:[],
                videoLikeList:[],
                videoPlayList:[],
                examList:[],
                selfTestList:[],
                courseYear:[],
                fontSize: 14,
                examColumns: [
                    {
                        title: "试卷名称",
                        key: "paperName",
                        align: 'center',
                        width:260,
                    },
                    {
                        title: "试卷类型",
                        key: "paperType",
                        align: 'center',
                        render: (h, params) => {
							let paperType = params.row.paperType == 'null' || !params.row.paperType || params.row.paperType == 'paper_fixed' ? '固定试卷':params.row.paperType == 'paper_reordering' ?'变序试卷':'随机试卷'
							return h('span', paperType)
						}
                    },
                    {
                        title: "参与人数",
                        key: "count",
                       align: 'center',
                    },{
                        title: "平均分",
                        key: "avgScore",
                        align: 'center',
                        render: (h, params) => {
                            return h('span', params.row.avgScore.toFixed(2))
                        }
                    },{
                        title: "最高分",
                        key: "maxScore",
                        align: 'center',
                    },{
                        title: "最低分",
                        key: "minScore",
                       align: 'center',
                    },
                ],
            }
		},
		created() {
			
		},
		filters: {

		},
		watch: {
		},
		mounted() {
			this.init()
            
		},
		methods: {
			init(){
                this.getStatisticRoles()
                this.getCountHotCourseAndExp()
                this.getVideoLikeList()
                this.getVideoPlayList()
                this.getStatisticCourseYear()
                this.getStatisticsExamPaper(0)
                this.getStatisticsExamPaper(1)
			},
            getVideoPlayList(){
                 let params={
                    pageIndex:1,
                    pageSize:10,
                    order:'desc',
                    sortBy:'playCounts'
                }
                queryStudyVideo(params).then(res=>{
                    if(res.code==1){
                        this.videoPlayList=res.data.items
                        this.videoPlayList=this.videoPlayList.reverse()
                        this.drawVideoPlay(this.videoPlayList)
                    }else{
                        this.$Message.warning(res.message)
                    }
                }).catch(error => {
					console.log(error)
				})
            },
            getVideoLikeList(){
                let params={
                    pageIndex:1,
                    pageSize:10,
                    order:'desc',
                    sortBy:'likesCounts'
                }
                queryStudyVideo(params).then(res=>{
                    if(res.code==1){
                        this.videoLikeList=res.data.items
                         this.videoLikeList=this.videoLikeList.reverse()
                        this.drawVideoLike(this.videoLikeList)
                    }else{
                        this.$Message.warning(res.message)
                    }
                }).catch(error => {
					console.log(error)
				})
            },
            getStatisticRoles(){
                getStatisticRoles().then(res=>{
                    if(res.data.code==1){
                        this.roleCountList=res.data.data.items
                        this.roleCountSum=res.data.data.sum
                        let maxPercent
						let sumPercent = 0
						this.roleCountList = this.roleCountList.map(item => {
							let percent = Number((item.count / this.roleCountSum).toFixed(4))
							maxPercent = maxPercent === undefined ? Math.max(0, percent) : Math.max(maxPercent, percent)
							sumPercent += percent
							item.percent = percent
							return item
						})
						if (sumPercent !== 0) { // 均不为0，计算最终四舍五入的结果的误差，并由最大的一个百分比来做零和
							let diff = 1 - sumPercent
							let item = this.roleCountList.find(item => item.percent === maxPercent)
							if (item) {
								item.percent += diff
							}
						}
                       this.drawRole(this.roleCountList)
                    }else{
                        this.$Message.warning(res.data.message)
                    }
                }).catch(error => {
					console.log(error)
				})
            },
            getCountHotCourseAndExp(){
                getCountHotCourseAndExp().then(res=>{
                    if(res.data.code==1){
                        this.hotCourseList=res.data.data.hotCourseList.slice(0,10)
                        this.hotExpList=res.data.data.hotExpList.slice(0,10)
                        this.drawCourse(this.hotCourseList)
                        this.drawExp(this.hotExpList)
                    }else{
                        this.$Message.warning(res.data.message)
                    }
                }).catch(error => {
					console.log(error)
				})
            },
            getStatisticCourseYear(){
                getStatisticCourseYear().then(res=>{
                    if(res.code==1){
                        this.courseYear=res.data
                        for(var i=0;i<this.courseYear.length;i++){
                            this.courseYear[i].dataList=this.courseYear[i].dataList.reverse()
                        }
                        this.drawCourseYear()
                    }else{
                        this.$Message.warning(res.message)
                    }
                }).catch(error => {
					console.log(error)
				})
            },
            getStatisticsExamPaper(type){
                getStatisticsExamPaper(type).then(res=>{
                    if(res.code==1){
                        if(type==0){
                            this.examList=res.data
                        }else{
                            this.selfTestList=res.data
                        }
                    }else{
                        this.$Message.warning(res.message)
                    }
                }).catch(error => {
					this.$Message.error(error)
				})
            },
            drawRole(data){
				const chart = new G2.Chart({
				container: 'rolePercentage',
				forceFit: true,
				height: 700
				});
				chart.source(data, {
					percent: {
						formatter: val => {
							val = (val * 100).toFixed(2) + '%';
							return val;
						}
					}
				});
				chart.coord('theta', {
					radius: 0.7,

				});
				chart.tooltip({
					useHtml:true,
					htmlContent:function(title,items){
						let point = items[0].point.point
						return '<div class="g2-tooltip" style="position:absolute;box-shadow: rgb(174 174 174) 0px 0px 10px; background-color: rgba(255, 255, 255, 0.9); border-radius: 4px;padding: 6px 10px;">'
							+ '<div class="g2-tooltip-title" style="margin-bottom: 4px;">'+point.roleName
						  +'</div>'
							+ '<ul class="g2-tooltip-list" ><li><span style="width:5px;height:5px;background:#ff9900;border-radius:50%;margin-bottom: 2px;margin-right:10px;display:inline-block"></span><span>百分比：</span><span style="padding-left:26px">'+(point.percent * 100).toFixed(2) +'%<span></li>'
							+'<li><span style="width:5px;height:5px;background:#19be6b;margin-bottom: 2px;border-radius:50%;margin-right:10px;display:inline-block"></span><span style="display: inline-block; width: 72px;">学习人数：</span><span style="padding-left:26px">'+point.count+'</span></li></ul>'
							+ '</div>'
					}
				})
				chart.intervalStack()
				.position('percent')
				.color('roleName')
				.label('percent', {
					formatter: (val, item) => {
						return item.point.roleName + ': ' + val;
					}
				})
				.style({
					lineWidth: 1,
					stroke: '#fff'
				});
				chart.render();
			},
            drawCourse(data){
                const chart = new G2.Chart({
                    container: 'Course',
                    forceFit: true,
                    height: 500,
                    padding: [ 20, 20, 50, 20 ]
                });
                chart.source(data);
                chart.scale('countNum', {
                alias: '收藏次数(次)'
                });
                chart.axis('name', {
                label: {
                    textStyle: {
                    fill: '#aaaaaa'
                    }
                },
                tickLine: {
                    alignWithLabel: false,
                    length: 0
                }
                });
                chart.axis('countNum', false);
                chart.tooltip({
                share: true
                });

                chart.interval().position('name*countNum').opacity(1)

                chart.render();
            },
            drawExp(data){
                const chart = new G2.Chart({
                    container: 'Exp',
                    forceFit: true,
                    height: 500,
                    padding: [ 20, 20, 50, 20 ]
                });
                chart.source(data);
                chart.scale('countNum', {
                alias: '收藏次数(次)'
                });
                chart.axis('name', {
                label: {
                    textStyle: {
                    fill: '#aaaaaa'
                    }
                },
                tickLine: {
                    alignWithLabel: false,
                    length: 0
                }
                });
                chart.axis('countNum', false);
                chart.tooltip({
                share: true
                });

                chart.interval().position('name*countNum').opacity(1)

                chart.render();
            },
            drawVideoLike(data){
                const chart = new G2.Chart({
                    container: 'videoLike',
                    forceFit: true,
                    height: 500,
                    padding: [ 20, 80 ]
                });
                chart.source(data, {
                    count: {
                        min:0
                    }
                });
                chart.coord('theta', {
                    innerRadius: 0.2,
                    endAngle: Math.PI
                });
                chart.interval()
                .position('name*likesCounts')
                .color('#8543e0')
                .shape('line')
                .select(false)
                .style({
                    lineAppendWidth: 10
                }); // 线状柱状图
                chart.point()
                .position('name*likesCounts')
                .color('#8543e0')
                .shape('circle');
                for (let i = 0, l = data.length; i < l; i++) {
                const obj = data[i];
                chart.guide().text({
                    position: [ obj.name, 0 ],
                    content: obj.name + ' ',
                    style: {
                    textAlign: 'right'
                    }
                });
                }
                chart.guide().text({
                position: [ '50%', '50%' ],
                content: 'TOP10',
                style: {
                    textAlign: 'center',
                    fontSize: 24,
                    fill: '#8543e0'
                }
                });
                chart.render();
            },
            drawVideoPlay(data){
                const chart = new G2.Chart({
                    container: 'videoPlay',
                    forceFit: true,
                    height: 500,
                    padding: [ 20, 80 ]
                });
                chart.source(data, {
                    count: {
                        min:0
                    }
                });
                chart.coord('theta', {
                    innerRadius: 0.2,
                    endAngle: Math.PI
                });
                chart.interval()
                .position('name*playCounts')
                .color('#8543e0')
                .shape('line')
                .select(false)
                .style({
                    lineAppendWidth: 10
                }); // 线状柱状图
                chart.point()
                .position('name*playCounts')
                .color('#8543e0')
                .shape('circle');
                for (let i = 0, l = data.length; i < l; i++) {
                const obj = data[i];
                chart.guide().text({
                    position: [ obj.name, 0 ],
                    content: obj.name + ' ',
                    style: {
                    textAlign: 'right'
                    }
                });
                }
                chart.guide().text({
                position: [ '50%', '50%' ],
                content: 'TOP10',
                style: {
                    textAlign: 'center',
                    fontSize: 24,
                    fill: '#8543e0'
                }
                });
                chart.render();
            },
            drawCourseYear(){
                let scoreOptione = {
					chart: {
						backgroundColor: 'transparent',
					},
					title: {
						text: 'TOP5',
						align: 'left',
						y: this.fontSize * 0.8,
						style: {
							fontSize: this.fontSize * 0.8 + 'px',
							fontWeight: 'bold',
							//		            color: 'red'   //这边是改标题的字体大小和颜色
						}
					},
					legend: {
						//        	floating: true,
						align: 'left',
						verticalAlign: 'top',
						itemStyle: {
							fontSize: this.fontSize * 0.6 + 'px',
							fontWeight: 'normal',
							//		            color: 'red'   //这边是改标题的字体大小和颜色
						}
					},
					xAxis: {
						categories: this.courseYear[0].dataList.map(score => score.year),
						labels: {
							style: {
								fontSize: this.fontSize * 0.6
							},
						},
					},
					plotOptions: {
						series: {
							label: {
								//connectorAllowed: false
							}
						}
					},
					yAxis: {
						title: {
							text: '排课(数量)'
						},
					},
					series: this.courseYear.map(user => {
						return {
							name: user.className,
							//type:'line',
							data: user.dataList.map(score => score.count)
						}
					}),
					credits: {
						enabled: false
					}, //去掉地址
					exporting: {
						enabled: false
					}, //隐藏导出图片
					responsive: {
						rules: [{
							condition: {
								maxWidth: 500
							},
							chartOptions: {
								legend: {
									layout: 'horizontal',
									align: 'left',
									verticalAlign: 'top'
								}
							}
						}]
					}
				};
				SeriesLabel(HighCharts);
				HighCharts.chart('scoreAnalysis', scoreOptione);
            }
		}
	}
</script>
<style scoped>
	.page-wrap {
		padding: 30px;
	}
	
	.page-content {
		border-radius: 10px;
		overflow: auto;
	}
	.page-header {
		display: flex;
		justify-content: space-between;
		padding: 20px 20px 0 20px;
		width: 100%;
	}
	.page-header .title{
		font-weight: 700;
		font-size: 18px;
	}
    .my-flex {
		display: flex;
        justify-content: space-between;
		margin-bottom: 20px;
	}
    .my-col {
		padding: 20px;
		border-radius: 10px;
		background-color: #FFF;
		position: relative;
		top: 0px;
		left: 0px;
		min-height: 500px;
	}
	.col-2 {
		width: calc(50% - 10px);
	}
    .col-1 {
		width: 100%;
	}
    #homer_Middle .title {
		font-size: 18px;
		color: #333;
		font-weight: 600;
	}
</style>